use std::str::FromStr;
use toml::value::{Datetime, Map};
use yaml_rust::Yaml;

pub fn common(yaml: Yaml) -> anyhow::Result<toml::Value> {
    match yaml {
        Yaml::Real(v) => Ok(toml::Value::String(v)),
        Yaml::Integer(v) => Ok(toml::Value::Integer(v)),
        Yaml::String(v) => Ok(toml::Value::String(v)),
        Yaml::Boolean(v) => Ok(toml::Value::Boolean(v)),
        Yaml::Array(list) => {
            let mut arr = Vec::new();
            for v in list {
                arr.push(common(v)?);
            }
            Ok(toml::Value::Array(arr))
        }
        Yaml::Hash(link_map) => {
            let mut map = Map::new();
            for (key, value) in link_map.into_iter() {
                let key = key.as_str().unwrap().to_string();

                map.insert(key, common(value)?);
            }
            Ok(toml::Value::Table(map))
        }
        _ => {
            println!("unexpected find {:?}", yaml);
            Ok(toml::Value::String("".to_string()))
        }
    }
}

pub fn zola(yaml: Yaml) -> anyhow::Result<toml::Value> {
    match yaml {
        Yaml::Real(v) => Ok(toml::Value::String(v)),
        Yaml::Integer(v) => Ok(toml::Value::Integer(v)),
        Yaml::String(v) => Ok(toml::Value::String(v)),
        Yaml::Boolean(v) => Ok(toml::Value::Boolean(v)),
        Yaml::Array(list) => {
            let mut arr = Vec::new();
            for v in list {
                arr.push(zola(v)?);
            }
            Ok(toml::Value::Array(arr))
        }
        Yaml::Hash(link_map) => {
            let mut map = Map::new();
            let mut taxonomies = Map::new();
            for (key, value) in link_map.into_iter() {
                let key = key.as_str().unwrap().to_string();

                match key.as_str() {
                    "date" => {
                        let dt = Datetime::from_str(value.as_str().unwrap())?;
                        map.insert(key, toml::Value::Datetime(dt));
                    }
                    "tags" | "categories" => {
                        let value = zola(value)?;
                        if value.is_array() {
                            taxonomies.insert(key, value);
                        } else {
                            taxonomies.insert(key, toml::Value::Array(vec![value]));
                        }
                    }
                    "title" => {
                        map.insert(key, zola(value)?);
                    }
                    _ => {}
                }
            }
            map.insert("taxonomies".to_string(), toml::Value::Table(taxonomies));
            Ok(toml::Value::Table(map))
        }
        _ => {
            println!("unexpected find {:?}", yaml);
            Ok(toml::Value::String("".to_string()))
        }
    }
}
